<template>
  <div>
    <a-modal
      v-dragModal
      ok-text="确认"
      cancel-text="取消"
      :maskClosable="false"
      :title="title"
      :width="1800"
      @cancel="handleClose"
      :destroyOnClose="true"
      @ok="handleOk"
      :visible="visible"
      footer=""
    >
      <template>
        <div class="modalBut">
          <!-- <a-button @click="handleClose">
            取消
          </a-button>
          <a-button @click="handleOk" type="primary">确认</a-button> -->
        </div>
      </template>
      <div>
        <a-card class="card-header">
          <div class="tool-bar">
            <a-button size="small" style="border: none;" @click="undo()">
              <img
                style="width: 22px;padding-right: 3px;"
                src="@images/equipment/cancel.png"
                alt=""
              />
              撤回
            </a-button>
            <a-button size="small" style="border: none;" @click="redo()">
              <img
                style="width: 22px;padding-right: 3px;"
                src="@images/equipment/resume.png"
                alt=""
              />
              恢复
            </a-button>
            <a-button size="small" style="border: none;" @click="textLeft">
              <a-icon type="pic-left" title="左对齐" />
              左对齐
            </a-button>
            <a-button size="small" style="border: none;" @click="textCenter">
              <a-icon type="pic-center" title="居中对齐" />
              居中
            </a-button>
            <a-button size="small" style="border: none;" @click="textRight">
              <a-icon type="pic-right" title="右对齐" />
              右对齐
            </a-button>
            <a-button size="small" style="border: none;" @click="topBorder">
              <a-icon type="border-top" title="上边框" />
              上边框
            </a-button>
            <a-button size="small" style="border: none;" @click="bottomBorder">
              <a-icon type="border-bottom" title="下边框" />
              下边框
            </a-button>
            <a-button size="small" style="border: none;" @click="leftBorder">
              <a-icon type="border-left" title="左边框" />
              左边框
            </a-button>
            <a-button size="small" style="border: none;" @click="rightBorder">
              <a-icon type="border-right" title="右边框" />
              右边框
            </a-button>
            <a-button size="small" style="border: none;" @click="boldFont">
              <a-icon type="bold" title="字体加粗" />
              粗体
            </a-button>
            <!-- 字体大小 -->
            <a-button size="small" style="border: none;">
              <a-dropdown
                :trigger="['click']"
                title="字体大小"
                @click="(e) => e.preventDefault()"
              >
                <a class="ant-dropdown-link">
                  <a-icon type="line-height" />
                  字号
                </a>
                <a-menu slot="overlay">
                  <a-menu-item
                    v-for="item in [10, 15, 20, 25, 30, 35]"
                    :key="item"
                  >
                    <a @click="setFontSize(item)">{{ item }}px</a>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </a-button>
            <!-- 字体格式 -->
            <!-- <a-dropdown :trigger="['click']" title="字体样式">
              <a class="ant-dropdown-link" @click="(e) => e.preventDefault()">
                <a-icon type="font-size" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item v-for="item in [10, 30]" :key="item">
                  <a>{{ item }} px</a>
                </a-menu-item>
              </a-menu>
            </a-dropdown> -->
            <a-button size="small" style="border: none;">
              <div ref="color">
                <img
                  style="width: 22px;"
                  src="@images/equipment/color.png"
                  alt=""
                />
                <span>颜色</span>
              </div>
            </a-button>
            <a-button size="small" style="border: none;">
              <div ref="bgColor">
                <img
                  style="width: 22px;"
                  src="@images/equipment/bgColor.png"
                  alt=""
                />
                <span>背景色</span>
              </div>
            </a-button>
            <!-- <a-icon type="check-square" title="多选框" @click="setCheckBox" /> -->
            <a-button size="small" style="border: none;" @click="setDate">
              <a-icon type="calendar" title="插入日期" />
              日期
            </a-button>
            <a-button size="small" style="border: none;" @click="setDropDown">
              <a-icon type="bars" title="插入下拉框" />
              下拉框
            </a-button>
            <a-button size="small" style="border: none;" @click="inputExecl">
              <a-icon type="folder-add" title="导入execl" />
              导入excel
            </a-button>
            <a-button size="small" style="border: none;" @click="saveToServe">
              <a-icon type="cloud-upload" title="保存" />
              保存excel
            </a-button>
            <a-button size="small" style="border: none;" @click="printExecl">
              <a-icon type="printer" title="打印选中" />
              打印excel
            </a-button>
            <a-button size="small" style="border: none;" @click="doPrint">
              <a-icon type="printer" title="打印选中" />
              打印工单
            </a-button>

            <!-- <a-icon type="arrow-left" title="撤回" @click="table.undo()" />
            <a-icon type="arrow-right" title="恢复" @click="table.redo()" />
            <a-icon type="pic-left" title="左对齐" @click="textLeft" />
            <a-icon type="pic-center" title="居中对齐" @click="textCenter" />
            <a-icon type="pic-right" title="右对齐" @click="textRight" />
            <a-icon type="border-top" title="上边框" @click="topBorder" />
            <a-icon type="border-bottom" title="下边框" @click="bottomBorder" />
            <a-icon type="border-left" title="左边框" @click="leftBorder" />
            <a-icon type="border-right" title="右边框" @click="rightBorder" />
            <a-icon type="bold" title="字体加粗" @click="boldFont" /> -->
            <!-- 字体大小 -->
            <!-- <a-dropdown :trigger="['click']" title="字体大小">
              <a class="ant-dropdown-link" @click="(e) => e.preventDefault()">
                <a-icon type="line-height" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item
                  v-for="item in [10, 15, 20, 25, 30, 35]"
                  :key="item"
                >
                  <a @click="setFontSize(item)">{{ item }}px</a>
                </a-menu-item>
              </a-menu>
            </a-dropdown> -->
            <!-- 字体格式 -->
            <!-- <a-dropdown :trigger="['click']" title="字体样式">
              <a class="ant-dropdown-link" @click="(e) => e.preventDefault()">
                <a-icon type="font-size" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item v-for="item in [10, 30]" :key="item">
                  <a>{{ item }} px</a>
                </a-menu-item>
              </a-menu>
            </a-dropdown> -->
            <!-- <div ref="color">
              <a-icon type="font-colors" title="更改字体颜色" />
            </div>
            <div ref="bgColor">
              <a-icon type="bg-colors" title="更改背景颜色" />
            </div> -->
            <!-- <a-icon type="check-square" title="多选框" @click="setCheckBox" /> -->
            <!-- <a-icon type="calendar" title="插入日期" @click="setDate" />
            <a-icon type="bars" title="插入下拉框" @click="setDropDown" />
            <a-icon type="folder-add" title="导入execl" @click="inputExecl" />
            <a-icon type="cloud-upload" title="保存" @click="saveToServe" />
            <a-icon type="printer" title="打印选中" @click="doPrint" /> -->
          </div>
          <DropDownModel ref="DropDown" @ok="DropDwonInputOk"></DropDownModel>
          <UploadImageModal
            ref="UploadImage"
            @ok="UploadImageOK"
          ></UploadImageModal>
          <AddPlanNameModal
            ref="AddPlanName"
            @ok="AddPlanNameOK"
          ></AddPlanNameModal>
          <div id="Excel" ref="spreadsheet"></div>
          <!-- 打印模板区 -->
          <div ref="tableRef" style="overflow: visible;" v-show="false">
            <PrintTemp :print-data="prints"></PrintTemp>
          </div>
        </a-card>
      </div>
    </a-modal>
  </div>
</template>
<script>
import XLSX from "xlsx";
import jexcel from "jspreadsheet-ce";
import "jspreadsheet-ce/dist/jspreadsheet.css";
import "jsuites/dist/jsuites.css";
import DropDownModel from "./components/DropDownModal.vue";
import PrintTemp from "./components/printTemp";
import AddPlanNameModal from "./components/AddPlanNameModal.vue";
import UploadImageModal from "./components/UploadImageModal.vue";
import { tableOption, content } from "./components/optionsConfig";
import api from "@/api/apiServer";
import { apiUrl } from "@/api/URLConfig";
import axois from "axios";
import moment from "moment";
import jSuites from "jsuites";

export default {
  components: {
    PrintTemp,
    DropDownModel,
    UploadImageModal,
    AddPlanNameModal,
  },
  data() {
    return {
      planId: null,
      importExecl: [],
      importSheetName: "",
      visible: false,
      title: "",
      id: "",
      productPlan: "",
      headName: {},
      prints: {
        "工艺-1": "",
        "工艺-2": "",
        "工艺-3": "",
        "工艺-4": "",
        "工艺-5": "",
        "工艺-6": "",
        "工艺-7": "",
        "工艺-8": "",
        "工艺-9": "",
        "工艺-10": "",
      },
      setWidthCol: [
        "图纸接收日期",
        "开始加工日期",
        "交货日",
        "交期",
        "入库时间",
        "协调交期",
        "工件图片",
      ],
      excelData: [],
    };
  },
  methods: {
    printExecl() {
      document.body.innerHTML = this.$refs["spreadsheet"].children[1].innerHTML;
      document.body.style.zoom = 0.25;
      window.print.portrait = false;
      window.print();
      window.location.reload();
    },
    AddPlanNameOK(planName) {
      console.log(planName);
      this.productPlan = planName;
      this.saveToServe();
    },
    handleClose() {
      this.visible = false;
      this.productPlan = "";
      this.$emit("ok");
    },
    handleOk() {
      this.visible = false;
      this.$emit("ok");
    },

    //表格渲染函数
    renderData(headData, tableDate) {
      //渲染表头
      // headData.forEach((item, index) => {
      //   window.table.setHeader(index, item);
      // });
      //渲染表体
      tableDate.unshift(headData);
      window.table.setData(tableDate);
      window.table.options.data[0].forEach((element, index) => {
        this.setWidthCol.includes(element) &&
          window.table.setWidth(index, "165");
      });
      // console.log(window.table.getMeta("A1"));
      window.table.refresh();
    },

    //保存到服务器
    async saveToServe() {
      // 获取并上传表头
      // let headData = {};
      // window.table
      //   .getHeaders()
      //   .split(",")
      //   .forEach((item, index) => {
      //     headData[index] = item;
      //   });
      // let titleRes = await api.AddOrUpdataTableHead(headData);

      //获取并上传表格数据
      let tableData = [];
      //筛出空数据并保存到数组
      window.table.getJson().forEach((element) => {
        let str = element[0] + "";
        if (str.trim()) {
          tableData.push(element);
        }
      });
      tableData.shift();
      let execlData = JSON.stringify(tableData);
      let params = {
        id: this.planId,
        productPlan: this.productPlan,
        excelData: execlData,
      };
      if (this.planId == -1) {
        if (this.productPlan) {
          let insert = {
            productPlan: this.productPlan,
            excelData: execlData,
          };
          let insertRes = await api.ProductPlanV2GetInsert(insert);
          this.title = `生产计划编号: ${this.productPlan}`;
          if(insertRes.code==200){
            this.$message.success(insertRes.message);
          }else{
            this.$message.error(insertRes.message);
          }

          this.planId = insertRes.data;
          this.id = insertRes.data;
        } else {
          this.$refs["AddPlanName"].modalShow();
        }
      } else if (this.planId == -2) {
        let insert = {
          productPlan: this.importSheetName,
          excelData: execlData,
        };
        let insertRes = await api.ProductPlanV2GetInsert(insert);
        if (insertRes.message == "生产计划单号唯一") {
          this.importSheetName = this.importSheetName.replace(
            /\d$/,
            (old) => Number(old) + 1
          );
          this.saveToServe();
        } else {
          this.$message.success(insertRes.message);
          this.title = `生产计划编号: ${this.importSheetName}`;
          this.productPlan = this.importSheetName;
          this.planId = insertRes.data;
          this.id = insertRes.data;
        }
      } else {
        let res = await api.ProductPlanV2Update(params);
        if(res.code==200){
          this.$message.success(res.message);
        }else{
          this.$message.error(res.message);
        }
        console.log(res);
      }
    },

    //获取execl数据
    async getExeclData(params) {
      //获取表头数据
      let headRes = await api.FindTableHead();
      let _head = JSON.parse(headRes.data.data);
      this.headName = _head;
      let headData = [];
      for (let item in _head) {
        headData[~~item] = _head[item];
      }
      //获取表格数据
      let res = await api.ProductPlanV2GetDetail(params);
      console.log(res);
      this.productPlan = res.data.productPlan;
      this.excelData = JSON.parse(res.data.excelData);
      console.log(res);
      this.renderData(headData, this.excelData);
    },

    // 获取打印数据
    doPrint() {
      //提取表格中要打印的数据
      let printData = [];
      let start = window.table.selectedContainer[1];
      let end = window.table.selectedContainer[3];
      for (let i = start; i <= end; i++) {
        if (window.table.options.data[i][0]) {
          if (
            !Boolean(String(window.table.options.data[i][0]).includes("序号"))
          ) {
            printData.push(window.table.options.data[i]);
          }
        }
      }
      if (printData.length < 1) {
        this.$message.error("暂无可打印的数据");
        return false;
      }
      this.printSelectData(printData);
    },

    //打印选中数据
    printSelectData(printArr) {
      let that = this;
      window.onafterprint = function() {
        if (printArr.length > 1) {
          that.printSelectData(printArr.slice(1));
        } else {
          window.location.reload();
        }
      };
      let _printobj = {};
      for (let item in printArr[0]) {
        _printobj[this.headName[item]] = printArr[0][item];
      }
      if(this.planId<0){
        this.$message.error("请先保存工单")
        return;
      }
      _printobj.id = this.id;
      this.prints = _printobj;
      this.$nextTick(() => {
        setTimeout(() => {
          let newstr = this.$refs.tableRef.innerHTML; // 获取需要打印的内容
          document.body.innerHTML = newstr;
          document.body.style = "";
          window.print();
        }, 200);
      });
    },

    //导入Execl
    inputExecl() {
      let that = this;
      let execlInput = document.createElement("input");
      execlInput.type = "file";
      execlInput.click();
      execlInput.addEventListener("change", function(e) {
        that.load(execlInput);
      });
    },

    //读取本地execl函数
    load(inputEl) {
      let wb;
      let that = this;
      let tableData = [[]];
      let obj = inputEl;
      if (!obj.files) {
        return;
      }
      let f = obj.files[0];
      let reader = new FileReader();
      reader.onload = function(e) {
        let data = e.target.result;
        wb = XLSX.read(data, {
          type: "binary", //以二进制的方式读取
          cellStyles: true,
        });
        console.log("wb: ", wb);
        //读取并设置表头
        let headReg = /^__EMPTY/;
        let headData = [];
        for (const key in XLSX.utils.sheet_to_json(
          wb.Sheets[wb.SheetNames[0]],
          {
            head: 0,
            defval: " ",
          }
        )[0]) {
          if (!headReg.test(key)) {
            headData.push(key.trim());
          }
        }
        let isAddPicCol = false;
        if (String(headData[3]).trim() != "工件图片") {
          headData.splice(3, 0, "工件图片");
          isAddPicCol = true;
        }
        XLSX.utils
          .sheet_to_json(wb.Sheets[wb.SheetNames[0]], { head: 0, defval: " " })
          .forEach((item) => {
            let itemArr = [];
            for (const key in item) {
              if (!headReg.test(key)) {
                itemArr.push(item[key]);
              }
            }
            if (isAddPicCol) {
              itemArr.splice(3, 0, "");
            }
            tableData.push(itemArr);
          });
        tableData.shift();
        that.renderData(headData, tableData);
      };
      reader.readAsBinaryString(f);
    },

    //上传图片完成
    UploadImageOK(imgData) {
      let td =
        window.table.tbody.children[window.table.selectedContainer[1]].children[
          window.table.selectedContainer[0] + 1
        ];

      let cellName = jexcel.getColumnNameFromId([
        window.table.selectedContainer[0],
        parseInt(window.table.selectedContainer[1]),
      ]);
      window.table.setValue(cellName, apiUrl + imgData, false);
      //将单元格的值设置为图片
      let img = document.createElement("img");
      img.src = apiUrl + imgData;
      img.title = imgData;
      td.innerHTML = "";
      td.appendChild(img);
    },

    //上传图片
    uploadImage() {
      let that = this;
      let imgInput = document.createElement("input");
      imgInput.type = "file";
      imgInput.click();
      imgInput.onchange = async function() {
        let file = imgInput.files[0];
        const isJpgOrPng =
          file.type === "image/jpeg" || file.type === "image/png";
        if (!isJpgOrPng) {
          that.$message.error("只能上传jpg,png!");
          return false;
        }
        const isLt2M = file.size / 1024 / 1024 < 20;
        if (!isLt2M) {
          that.$message.error("文件最大20MB!");
          return false;
        }
        let formData = new FormData();
        formData.append("file", imgInput.files[0]);
        let res = await axois.post(apiUrl + "/fileLocal/uploads", formData);
        if (res.data.code == 200) {
          that.$message.success(res.data.message);
          that.UploadImageOK(res.data.data);
        } else {
          that.$message.error(res.data.message);
        }
      };
    },

    //设置单元格样式
    setCellStyle(attr, value) {
      let userSelectArea = window.table.selectedContainer;

      for (let i = userSelectArea[0]; i <= userSelectArea[2]; i++) {
        for (let j = userSelectArea[1]; j <= userSelectArea[3]; j++) {
          let cellName = jexcel.getColumnNameFromId([i, parseInt(j)]);
          window.table.setStyle(cellName, attr, value);
        }
      }
    },
    undo() {
      window.table.undo();
    },
    redo() {
      window.table.redo();
    },
    textLeft() {
      this.setCellStyle("text-align", "left");
    },
    textRight() {
      this.setCellStyle("text-align", "right");
    },
    textCenter() {
      this.setCellStyle("text-align", "center");
    },
    topBorder() {
      this.setCellStyle("border-top", "1px solid black");
    },
    bottomBorder() {
      this.setCellStyle("border-bottom", "1px solid black");
    },
    leftBorder() {
      this.setCellStyle("border-left", "1px solid black");
    },
    rightBorder() {
      this.setCellStyle("border-right", "1px solid black");
    },
    boldFont() {
      this.setCellStyle("font-weight", "bold");
    },
    setFontSize(size) {
      this.setCellStyle("font-size", size + "px");
    },

    setDate() {
      let td =
        window.table.tbody.children[~~window.table.selectedContainer[1]]
          .children[~~window.table.selectedContainer[0] + 1];
      var info = td.getBoundingClientRect();
      var editor = document.createElement("div");
      editor.style.width = info.width + "px";
      editor.style.height = info.height - 2 + "px";
      editor.style.minHeight = info.height - 2 + "px";
      td.classList.add("editor");
      td.innerHTML = "";
      td.appendChild(editor);

      let input = document.createElement("input");
      td.innerHTML = "";
      td.append(input);

      // 初始化时间
      window.table.options.data[~~window.table.selectedContainer[1]][
        ~~window.table.selectedContainer[0]
      ] = moment().format("YYYY-MM-DD");

      jSuites.calendar(td.children[0], {
        format: "YYYY/MM/DD",
        time: true,
        today: true,
        months: [
          "1月",
          "2月",
          "3月",
          "4月",
          "5月",
          "6月",
          "7月",
          "8月",
          "9月",
          "10月",
          "11月",
          "12月",
        ],
        monthsFull: [
          "1月",
          "2月",
          "3月",
          "4月",
          "5月",
          "6月",
          "7月",
          "8月",
          "9月",
          "10月",
          "11月",
          "12月",
        ],
        weekdays: ["日", "一", "二", "三", "四", "五", "六"],
        textReset: "重置",
        textDone: "完成",
        textUpdate: "更新",
        onchange: function(e, afterTime) {
          window.table.options.data[~~window.table.selectedContainer[1]][
            ~~window.table.selectedContainer[0]
          ] = afterTime;
        },
        // onopen:function(){
        //   this.value=window.table.options.data[~~window.table.selectedContainer[1]][
        //     ~~window.table.selectedContainer[0]
        //   ];
        // }
      });
      window.table.setWidth(window.table.selectedContainer[0], "125");
    },

    setDropDown() {
      this.$refs.DropDown.modalShow();
    },

    DropDwonInputOk(str) {
      let data = [];
      str.split(";").forEach((item, index) => {
        let obj = {};
        obj.value = item + "";
        obj.text = item + "";
        data.push(obj);
      });
      let td = this.table.tbody.children[this.table.selectedContainer[1]]
        .children[this.table.selectedContainer[0] + 1];

      var info = td.getBoundingClientRect();
      var editor = document.createElement("div");
      editor.style.width = info.width + "px";
      editor.style.height = info.height - 2 + "px";
      editor.style.minHeight = info.height - 2 + "px";
      td.classList.add("editor");
      td.innerHTML = "";
      td.appendChild(editor);

      let div = document.createElement("div");
      td.innerHTML = "";
      td.append(div);

      jSuites.dropdown(td.children[0], {
        data: data,
      });
    },
    async onLoadExcel() {
      let that = this;
      content.scoop = this;
      this.id = Number(this.planId);
      window.table = jexcel(this.$refs.spreadsheet, tableOption);
      let _table = window.table;
      Object.assign(this, { _table });
      if (this.planId > 0) {
        this.getExeclData({ id: this.planId });
      } else if (this.planId == -1) {
        console.log(this.importExecl);
        //获取表头数据
        let headRes = await api.FindTableHead();
        let _head = JSON.parse(headRes.data.data);
        this.headName = _head;
        let headData = [];
        for (let item in _head) {
          headData[~~item] = _head[item];
        }
        this.renderData(headData, []);
      } else if (this.planId == -2) {
        console.log(this.importExecl);
        //获取表头数据
        let headRes = await api.FindTableHead();
        let _head = JSON.parse(headRes.data.data);
        this.headName = _head;
        let headData = [];
        for (let item in _head) {
          headData[~~item] = _head[item];
        }
        this.renderData(headData, this.importExecl);
      }
      jSuites.color(this.$refs.color, {
        resetLabel: "重置",
        doneLabel: "完成",
        onchange: function(e, color) {
          that.setCellStyle("color", color);
        },
      });
      jSuites.color(this.$refs.bgColor, {
        resetLabel: "重置",
        doneLabel: "完成",
        onchange: function(e, color) {
          that.setCellStyle("background-color", color);
        },
      });
      window.table.refresh();
    },
    modalAdd() {
      this.visible = true;
      setTimeout(
        this.$nextTick(() => {
          this.onLoadExcel();
        }),
        300
      );
    },
  },
  mounted() {
    // let that=this;
    // document.onkeydown =function (e) {
    //   e.preventDefault();
    //   var currKey = 0,
    //     e = e || event || window.event;
    //   currKey = e.keyCode || e.which || e.charCode;
    //   if (currKey == 83 && (e.ctrlKey || e.metaKey)) {
    //     that.saveToServe();
    //   }
    //   //断开事件链阻止jexecl默认的快捷键事件触发
    //   e.stopImmediatePropagation();
    // }
  },
};
</script>

<style lang="less" scoped>
::v-deep .ant-card-body {
  padding: 0px;
}

::v-deep .ant-card-bordered {
  border: 0px solid #e8e8e8;
}

.color-box {
  position: relative;
}
.color-select {
  position: absolute;
  bottom: 0;
}
::v-deep .jexcel_toolbar {
  & > i {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 3px;
  }
}
#Excel {
  width: 100%;
}
.tool-bar {
  height: 32px;
  display: flex;
  align-items: center;
  border: 1px solid #ccc;
  padding: 4px;
  margin: 0px 2px 4px 1px;
  top: 0px;
  i:hover {
    background-color: #f3f3f3;
  }
  // i {
  //   display: flex;
  //   justify-content: center;
  //   align-items: center;
  //   height: 26px;
  //   width: 26px;
  //   margin-left: 5px;
  // }
  // a {
  //   display: flex;
  //   width: 32px;
  //   color: #595959;
  // }

  ::v-deep .ant-btn {
    // font-size: 12px;
    margin-right: 4px;
    span {
      font-size: 12px;
    }
  }
}

.card-header {
  margin: 0px 0;
}

::v-deep .jexcel_toolbar {
  & > i {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 3px;
  }
}
::v-deep .jexcel_search {
  box-sizing: border-box;
  border: 1px solid lightgray;
  border-radius: 15px;
  padding: 2px 10px;
}
</style>
